<?php

namespace Sharks\Core\Http\Form;

use Sharks\Core\Support\Bag\ParameterBag;
use Sharks\Core\Support\Base\Precondition;

/**
 * 表单验证类
 */
class FormValidator {

    private $fieldBag;

    public function __construct() {
        $this->fieldBag = new ParameterBag();
    }

    public function field($field) {
        $formField = new FormField($field, $_REQUEST);
        $this->fieldBag->put($field, $formField);
        return $formField;
    }

    public function hasError($field = null) {
        if (is_null($field)) {
            foreach ($this->fieldBag->all() as $field => $formField) {

                if (true == $formField->hasError()) {
                    return true;
                }
            }
        }
        elseif ($this->fieldBag->has($field) && $this->fieldBag->get($field)->hasError()) {
            return true;
        }
        return false;
    }

    public function getErrors() {
        $errors = array();
        foreach ($this->fieldBag->all() as $field => $formField) {
            if ($formField->hasError()) {
                foreach ($formField->getErrors() as $error) {
                    array_push($errors, $error);
                }
            }
        }
        return $errors;
    }

    public function getError($field) {
        Precondition::check($this->fieldBag->has($field), "找不到相关$field");

        $formField = $this->fieldBag->get($field);
        if ($formField->hasError()) {
            return $formField->getErrors();
        }
        return array();
    }

    public function getErrorMsg($field) {
        return $this->getError($field)[0]['msg'];
    }
}